package x.trident.core.config.center.context;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.ConfigurableEnvironment;

import java.util.Properties;


/**
 * 初始化NacosClient单例
 * 此类的使用必须激活 ConfigInitListener
 *
 * @author 林选伟
 * @date 2021/2/26 18:27
 */
@Slf4j
@Getter
public class NacosConfigContext {
    private static String defaultGroup = "DEFAULT_GROUP";
    private static ConfigService configService = null;

    private NacosConfigContext() {
    }

    /**
     * 初始化yml参数
     *
     * @param environment yml配置
     */
    public static void initConfigService(ConfigurableEnvironment environment) throws NacosException {
        String serverAddr = environment.getProperty("spring.cloud.nacos.config.server-addr");
        String namespace = environment.getProperty("spring.cloud.nacos.config.namespace");
        defaultGroup = environment.getProperty("spring.cloud.nacos.config.group");

        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
        properties.put(PropertyKeyConst.NAMESPACE, namespace);
        configService = NacosFactory.createConfigService(properties);
        log.info("[SUCCESS] nacos client 初始化完成");
    }

    public static ConfigService getConfigService() {
        return configService;
    }

    public static String getGroup() {
        return defaultGroup;
    }

}
